package com.ydl.shopping.controller.shopping;

import com.ydl.shopping.annotation.Logger;
import com.ydl.shopping.core.controller.BaseController;
import com.ydl.shopping.core.vo.ResultVO;
import com.ydl.shopping.domain.TbGoods;
import com.ydl.shopping.service.ITbGoodsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 商品相关接口
 *
 * restful
 * get 查询
 * post 新增
 * put 修改
 * delete 删除
 *
 * @author 林武泰
 */
@RestController
@CrossOrigin
@RequestMapping("/shopping/goods")
@Tag(name = "商品Controller")
public class TbGoodsController extends BaseController {
    @Resource
    private ITbGoodsService service;

    @GetMapping("/{id}")
    @PreAuthorize("hasAnyAuthority('goods:query')")
    @Operation(summary = "根据id查询商品")
    @Logger(model = "商品管理")
    public ResultVO getById(@PathVariable("id") Long id) {
        return success(service.getById(id));
    }

    @PostMapping("/list")
    @PreAuthorize("hasAnyAuthority('goods:query')")
    @Operation(summary = "查询商品列表")
    @Logger(model = "商品管理")
    public ResultVO list(@RequestBody TbGoods entity) {
        // 获取页码
        Long pageNumber = entity.getPageNumber();
        // 获取页数
        Long pageSize = entity.getPageSize();
        // 开启分页
        startPage(pageNumber, pageSize);

        return getPageResult(service.list(service.queryWrapper(entity)));
    }

    @PostMapping
    @PreAuthorize("hasAnyAuthority('goods:save')")
    @Operation(summary = "新增商品")
    @Logger(model = "商品管理")
    public ResultVO save(@Validated @RequestBody TbGoods entity) {
        entity.setCreateBy(username());
        return toResult(service.save(entity));
    }

    @PutMapping
    @PreAuthorize("hasAnyAuthority('goods:update')")
    @Operation(summary = "修改商品")
    @Logger(model = "商品管理")
    public ResultVO update(@Validated @RequestBody TbGoods entity) {
        entity.setUpdateBy(username());
        return toResult(service.updateById(entity));
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyAuthority('goods:delete')")
    @Operation(summary = "删除商品")
    @Logger(model = "商品管理")
    public ResultVO deleteById(@PathVariable("id") Long id) {
        return toResult(service.removeById(id));
    }

    @DeleteMapping
    @PreAuthorize("hasAnyAuthority('goods:delete')")
    @Operation(summary = "批量删除商品")
    @Logger(model = "商品管理")
    public ResultVO deleteByIds(@RequestParam List<Long> ids) {
        return toResult(service.removeByIds(ids));
    }
}
